package at.fhj.mobsecdev.cookit.webrequests;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import at.fhj.mobsecdev.cookit.model.Ingredient;
import at.fhj.mobsecdev.cookit.model.Recipe;

/**
 * Parses JSON responses from the web service
 */
public class JsonParser {
	
	/**
	 * Parses JSON recipe string recieved from the web service
	 * @param jsonString raw json string
	 * @return parsed recipes in a list
	 * @throws JSONException if web service response is malformed
	 */
	public List<Recipe> parseRecipeList(String jsonString) throws JSONException
	{
			List<Recipe> recipeList = new ArrayList<Recipe>();
			JSONArray recipeArray = new JSONArray(jsonString);
			
			for(int i=0; i < recipeArray.length(); i++)
			{
				final JSONObject jsonRecipe = recipeArray.getJSONObject(i);
				
				Recipe recipe = new Recipe();
				recipe.setName(jsonRecipe.getString("name"));
				recipe.setCookingInstruction(jsonRecipe.getString("cookingInstruction"));
				recipe.setOwnerUsername(jsonRecipe.getString("ownerUsername"));
				recipe.setDifficulty(jsonRecipe.getString("difficulty"));
				recipe.setIsVegetarian(jsonRecipe.getBoolean("vegetarian"));
				recipe.setImageFilePath(jsonRecipe.getString("imageFilePath"));
				
				
				List<Ingredient> ingredientList = new ArrayList<Ingredient>();
				JSONArray ingredientsArray = jsonRecipe.getJSONArray("ingredients");
				
				for(int j=0; j < ingredientsArray.length(); j++)
				{
					final JSONObject jsonIngredient = ingredientsArray.getJSONObject(j);
				 
					Ingredient ingredient = new Ingredient();
					ingredient.setAmount(jsonIngredient.getString("amount"));
					ingredient.setFood(jsonIngredient.getString("food"));
					
					ingredientList.add(ingredient);
				}
				
				recipe.setIngredients(ingredientList);
				recipeList.add(recipe);
			}
			
			return recipeList;
	}
}
